using System;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress;
using ZecaFil.DataSet;

namespace ZecaFil.Controls
{
    public partial class SalesXtraUserControl : XtraUserControl, IGridView
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.SaleSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public SalesXtraUserControl()
        {
            InitializeComponent();
            FormatGrid();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            VendasDataSet dataSet = _controller.GetSales();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Venda.TableName;
            FormatGrid();
        }

        private void FormatGrid()
        {
            gridView.OptionsView.ShowFooter = true;
            DevExpressHelper.SetColumnAsNumericAndPaint(colQuantidade);
            DevExpressHelper.SetColumnAsCurrency(colValor);
        }

        private void ShowDocument(long documentId)
        {
            var window = new SaleXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion

        public void AddDocument()
        {
            ShowDocument(-1);
        }

        public void PrintDocument()
        {
            var document = (VendasDataSet.VendaRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            _controller.PrintSale(document.Id);
        }

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "SalesXtraUserControl"; }
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var document = (VendasDataSet.VendaRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            ShowDocument(document.Id);
        }
    }
}
